<template>
	<view>
		<!-- Tab导航 -->
		<view class="tab-container">
			<view class="tab-item" :class="{ 'active': currentTab === 0 }" @click="switchTab(0)">
				全部订单
			</view>
			<view class="tab-item" :class="{ 'active': currentTab === 1 }" @click="switchTab(1)">
				待评价
			</view>
			<view class="tab-item" :class="{ 'active': currentTab === 2 }" @click="switchTab(2)">
				已评价
			</view>
		</view>

		<!-- 内容区域 -->
		<view class="content">
			<view v-if="currentTab === 0">
				<!-- 全部订单内容 -->
				<view v-if="filteredOrders.length > 0" class="order-list">
					<view v-for="order in filteredOrders" :key="order.id" class="order-item"
						@click="handleOrderClick(order)">
						<view class="order-header">
							<text class="order-id">订单号：{{ order.orderId }}</text>
							<text class="order-status">{{ getOrderStatus(order.orderStatus) }}</text>
						</view>
						<view class="order-product">
							<img class="order-image" :src="order.orderProductList[0].productImage"  />
							<text class="order-name">{{ order.orderProductList[0].productName }}</text>
						</view>
						<view class="order-content">
							<text class="order-amount">订单金额：¥{{ order.orderAmount }}</text>
							<text class="order-time">下单时间：{{ formatTime(order.createTime) }}</text>
						</view>
					</view>
				</view>
				<view v-else class="empty-state">
					<text>暂无订单</text>
				</view>
			</view>
			<view v-else-if="currentTab === 1">
				<!-- 待评价内容 -->
				<view v-if="getPendingReviews().length > 0" class="order-list">
					<view v-for="order in getPendingReviews()" :key="order.id" class="order-item"
						@click="goToReview(order)">
						<view class="order-header">
							<text class="order-id">订单号：{{ order.orderId }}</text>
							<text class="order-status">待评价</text>
						</view>
						<view class="order-content">
							<text class="order-amount">订单金额：¥{{ order.orderAmount }}</text>
							<text class="order-time">下单时间：{{ formatTime(order.createTime) }}</text>
						</view>
					</view>
				</view>
				<view v-else class="empty-state">
					<text>暂无待评价订单</text>
				</view>
			</view>
			<view v-else-if="currentTab === 2">
				<!-- 已评价内容 -->
				<view v-if="reviewedOrders.length > 0" class="order-list">
					<view v-for="order in reviewedOrders" :key="order.id" class="order-item"
						@click="goToOrderDetail(order)">
						<view class="order-header">
							<text class="order-id">订单号：{{ order.id }}</text>
							<text class="order-status">已评价</text>
						</view>
						<view class="order-content">
							<text class="order-id">商品名：{{ order.productName }}</text>
							<text class="order-amount">评价：{{ order.reviewContent }}</text>
							<text class="order-time">评价时间：{{ formatReviewTime(order.reviewTime) }}</text>
						</view>
					</view>
				</view>
				<view v-else class="empty-state">
					<text>暂无已评价订单</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { get, post, put } from '@/config/request.js'
import { getCurrentMemberId } from '@/utils/userState.js'

export default {
	data() {
		return {
			currentTab: 1, // 默认选中全部订单
			orderList: [],
			reviewedOrders: [], // 已评价订单列表
			memberId: null
		}
	},
	onLoad() {
		this.initUserInfo();
		this.getOrderList();
		this.getReviewedOrders();
	},
	computed: {
		filteredOrders() {
			// 过滤出当前用户的订单
			if (!this.memberId || !this.orderList || this.orderList.length === 0) {
				return [];
			}
			const userOrders = this.orderList.filter(order => {
				const orderMemberId = order.memberId;
				const isUserOrder = orderMemberId && orderMemberId.toString() === this.memberId.toString();
				console.log(`订单${order.id}的memberId: ${orderMemberId}, 当前用户ID: ${this.memberId}, 是否匹配: ${isUserOrder}`);
				return isUserOrder;
			});
			return userOrders;
		}
	},
	methods: {
		// 初始化用户信息
		initUserInfo() {
			this.memberId = getCurrentMemberId();
			console.log('当前用户ID:', this.memberId);
		},

		switchTab(index) {
			this.currentTab = index;
			console.log('切换到tab:', index);

			// 如果切换到已评价tab且没有数据，则重新获取
			if (index === 2 && this.reviewedOrders.length === 0) {
				this.getReviewedOrders();
			}
		},

		async getOrderList() {
			try {
				const res = await get('/orders/order/list', {
					pageNum: 1,
					pageSize: 50
				});
				console.log('订单列表API响应:', res);
				console.log('API返回数据结构:', {
					code: res.code,
					hasRows: !!res.rows,
					hasData: !!res.data,
					rowsType: res.rows ? typeof res.rows : 'undefined',
					dataType: res.data ? typeof res.data : 'undefined',
					rowsLength: res.rows ? res.rows.length : 0,
					dataLength: res.data ? (Array.isArray(res.data) ? res.data.length : 'not array') : 0
				});

				if (res.code === 200) {
					// 根据API返回的数据结构处理
					if (res.rows && Array.isArray(res.rows)) {
						// 如果直接返回rows数组
						this.orderList = res.rows;
					} else if (res.data && Array.isArray(res.data)) {
						// 如果返回data数组
						this.orderList = res.data;
					} else if (res.data && res.data.rows && Array.isArray(res.data.rows)) {
						// 如果返回data.rows数组
						this.orderList = res.data.rows;
					} else if (res.data && res.data.list && Array.isArray(res.data.list)) {
						// 如果返回data.list数组
						this.orderList = res.data.list;
					} else {
						this.orderList = [];
					}
					console.log('订单列表:', this.orderList);
				} else {
					this.orderList = [];
					console.log('获取订单列表失败:', res.msg || res.message);
				}
			} catch (error) {
				console.error('获取订单列表出错:', error);
				this.orderList = [];
			}
		},
		//不想写了，我的订单里面订单详情页面的数据结构和这个不一样，我懒得改了
		goToOrderDetail(order) {
			uni.navigateTo({
				url: `/pages/dingdanxiangqing/dingdanxiangqing?orderId=${order.id}&orderData=${encodeURIComponent(JSON.stringify(order))}`
			});
		},

		// 获取待评价订单
		getPendingReviews() {
			return this.filteredOrders.filter(order => {
				// 根据订单状态判断是否为待评价
				// 只显示已收货状态的订单，这些订单可以评价
				return order.orderStatus === '已收货' || order.orderStatus === 'RECEIVED';
			});
		},

		// 获取已评价订单
		async getReviewedOrders() {
			try {
				const res = await get('/huiyuan/reviews/list', {
					pageNum: 1,
					pageSize: 10,
					memberId: this.memberId
				});
				console.log('已评价订单API响应:', res);

				if (res.code === 200) {
					// 根据API返回的数据结构处理
					if (res.rows && Array.isArray(res.rows)) {
						this.reviewedOrders = res.rows;
					} else if (res.data && Array.isArray(res.data)) {
						this.reviewedOrders = res.data;
					} else if (res.data && res.data.rows && Array.isArray(res.data.rows)) {
						this.reviewedOrders = res.data.rows;
					} else if (res.data && res.data.list && Array.isArray(res.data.list)) {
						this.reviewedOrders = res.data.list;
					} else {
						this.reviewedOrders = [];
					}
					console.log('已评价订单列表:', this.reviewedOrders);
				} else {
					this.reviewedOrders = [];
					console.log(res);
					console.log('获取已评价订单失败:', res.msg || res.message);
				}
			} catch (error) {
				console.error('获取已评价订单出错:', error);
				this.reviewedOrders = [];
			}
		},

		// 获取订单状态显示文本
		getOrderStatus(status) {
			// 如果状态已经是中文，直接返回
			if (typeof status === 'string' && /[\u4e00-\u9fa5]/.test(status)) {
				return status;
			}
			const statusMap = {
				'PENDING': '待付款',
				'PAID': '已付款',
				'SHIPPED': '已发货',
				'RECEIVED': '已收货',
				'COMPLETED': '已完成',
				'REVIEWED': '已评价',
				'CANCELLED': '已取消'
			};
			return statusMap[status] || status || '未知状态';
		},

		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return '';
			const date = new Date(timestamp);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
		},

		// 格式化评价时间（年月日时分秒）
		formatReviewTime(timestamp) {
			if (!timestamp) return '';
			const date = new Date(timestamp);
			return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
		},

		// 判断订单是否可以评价
		isOrderCanReview(order) {
			return order.orderStatus === '已收货' || order.orderStatus === 'RECEIVED';
		},

		// 处理订单点击事件
		handleOrderClick(order) {
			// 如果是已收货状态，跳转到评价页面
			if (this.isOrderCanReview(order)) {
				this.goToReview(order);
			} else {
				// 其他状态跳转到订单详情页面
				this.goToOrderDetail(order);
			}
		},

		// 跳转到评价页面
		goToReview(order) {
			uni.navigateTo({
				url: `/pages/pingjia/pingjia?orderId=${order.id}&orderData=${encodeURIComponent(JSON.stringify(order))}`
			});
		}
	}
}
</script>

<style>
.tab-container {
	display: flex;
	background-color: #FFFFFF;
	padding: 15px 0;
	border-bottom: 1px solid #F0F0F0;
}

.tab-item {
	flex: 1;
	text-align: center;
	font-size: 14px;
	color: #666666;
	padding: 8px 0;
	position: relative;
}

.tab-item.active {
	color: hsl(6, 91%, 50%);
	font-weight: 500;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: -15px;
	left: 50%;
	transform: translateX(-50%);
	width: 20px;
	height: 2px;
	background-color: #f20d0d;
}

.content {
	padding: 20px;
}

.order-list {
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.order-item {
	background-color: #FFFFFF;
	border-radius: 8px;
	padding: 15px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.order-product {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
}

.order-image {
	width: 60px;
	height: 60px;
	border-radius: 8px;
	object-fit: cover;
	margin-right: 10px;
}

.order-product-name {
	font-size: 14px;
	color: #333;
	font-weight: 500;
}

.order-name {
	font-size: 14px;
	color: #333;
	font-weight: 500;
}

.order-id {
	font-size: 14px;
	color: #333;
	font-weight: 500;
}

.order-status {
	font-size: 12px;
	color: #f20d0d;
	background-color: #fff0f0;
	padding: 4px 8px;
	border-radius: 12px;
}

.order-content {
	display: flex;
	flex-direction: column;
	gap: 5px;
	margin-bottom: 10px;
}

.order-amount {
	font-size: 16px;
	color: #e00f0f;
	font-weight: 550;
}

.order-time {
	font-size: 12px;
	color: #999;
}

.order-actions {
	display: flex;
	justify-content: flex-end;
}

.review-btn {
	background-color: #f20d0d;
	color: #FFFFFF;
	border: none;
	border-radius: 20px;
	padding: 8px 20px;
	font-size: 14px;
}

.empty-state {
	text-align: center;
	padding: 60px 20px;
	color: #999;
	font-size: 16px;
}
</style>
